import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:im_module/model/LocationBean.dart';
import 'package:im_module/provider/im_provider.dart';
import 'package:provider/provider.dart';

/// State 基类
class BMFBaseMapState<T extends StatefulWidget> extends State<T> {
  BMFMapController? myMapController;

  Size? screenSize;
  String? currentCity;
  double? currentLatitude;
  double? currentLongitude;
  bool isSearch = true; //是否检索

  //是否移动到当前位置
  bool moveCurrent = true;

  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;
    return MaterialApp(
      home: Scaffold(),
    );
  }

  /// 创建完成回调
  void onBMFMapCreated(BMFMapController controller) {
    myMapController = controller;

    /// 地图加载回调
    myMapController?.setMapDidLoadCallback(callback: () {
      print('mapDidLoad-地图加载完成');

      loadMapSuccess();

      //移动当前定位的位置
      if (moveCurrent) {
        initLocation();
      }
    });
  }

  ///加载成功
  void loadMapSuccess(){

  }


  ///移动到定位点
  void initLocation() async {
    ///开启地图定位
    myMapController?.showUserLocation(true);

    LocationBean? _mLocationBean =
        Provider.of<ImProvider>(context, listen: false).mLocationBean;

    if (_mLocationBean?.latitude == 0 || _mLocationBean?.longitude == 0) {
      return;
    }

    currentCity = _mLocationBean?.province;
    currentLatitude = _mLocationBean?.latitude;
    currentLongitude = _mLocationBean?.longitude;

    moveMap(_mLocationBean?.latitude, _mLocationBean?.longitude, true);
  }

  void moveMap(double? latitude, double? longitude, bool search) {
    this.isSearch = search;
    if (myMapController != null) {
      myMapController?.setCenterCoordinate(
          BMFCoordinate(latitude, longitude), true,
          animateDurationMs: 1000);
    }
  }

  void moveCurrentLocation() {
    moveMap(currentLatitude, currentLongitude, true);
  }

  @override
  void dispose() {
    super.dispose();
  }

  /// 设置地图参数
  BMFMapOptions initMapOptions() {
    BMFMapOptions mapOptions = BMFMapOptions(
      center: BMFCoordinate(39.917215, 116.380341),
      zoomLevel: 18,
      showMapScaleBar: false,
    );
    return mapOptions;
  }

  /// 创建地图
  Container generateMap() {
    return Container(
      height: screenSize?.height,
      width: screenSize?.width,
      child: BMFMapWidget(
        onBMFMapCreated: (controller) {
          onBMFMapCreated(controller);
        },
        mapOptions: initMapOptions(),
      ),
    );
  }

  /// 创建控制栏
  Widget generateControlBar() {
    throw UnimplementedError();
  }
}
